package com.supercube.sport.yoga.controller;

import com.github.pagehelper.PageInfo;
import com.supercube.common.controller.BaseController;
import com.supercube.common.utils.StringUtils;
import com.supercube.common.utils.TimeUtils;
import com.supercube.sport.yoga.bo.MemberCardInfoBO;
import com.supercube.sport.yoga.dao.MemberCardBindingInfoMapper;
import com.supercube.sport.yoga.domain.*;
import com.supercube.sport.yoga.service.MemberCardBindingInfoService;
import com.supercube.sport.yoga.service.MemberCardService;
import com.supercube.sport.yoga.utils.ResultInfo;
import com.supercube.sport.yoga.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/memberCardController")
@Api(tags = "会员卡信息")
public class MemberCardController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MemberCardService memberCardService;

    @Autowired
    MemberCardBindingInfoService memberCardBindingInfoService;

    @Autowired
    private MemberCardBindingInfoMapper memberCardBindingInfoMapper;

    @ApiOperation(value = "保存会员卡信息", notes = "保存会员卡信息")
    @PostMapping("/save")
    public ResultInfo saveMemberCardInfo(@RequestBody MemberCardInfoBO cardInfoBO) {
        MemberCardBasicInfoDTO dto = new MemberCardBasicInfoDTO();
        String cardId = UUID.randomUUID().toString();
        setMemberCardInfo(cardInfoBO, dto, cardId);

        CardSuperSettingsDTO cardSuperSettingsDTO = dto.getCardSuperSettingsDTO();
        if (cardSuperSettingsDTO != null) {
            cardSuperSettingsDTO.setCardId(cardId);
            cardSuperSettingsDTO.setId(UUID.randomUUID().toString());
        }
        CardTransferSettingsDTO cardTransferSettingsDTO = dto.getCardTransferSettingsDTO();
        if (cardTransferSettingsDTO != null) {
            cardTransferSettingsDTO.setCardId(cardId);
            cardTransferSettingsDTO.setId(UUID.randomUUID().toString());
        }
        List<CoursesSupportedCardDTO> coursesSupportedCardDTOS = dto.getCoursesSupportedCardDTOS();
        if (CollectionUtils.isNotEmpty(coursesSupportedCardDTOS)) {
            coursesSupportedCardDTOS.forEach(coursesSupportedCardDTO -> {
                coursesSupportedCardDTO.setCardId(cardId);
                coursesSupportedCardDTO.setId(UUID.randomUUID().toString());
            });
        }
        List<SettingPriceGradientDTO> settingPriceGradientDTOS = dto.getSettingPriceGradientDTOS();
        if (CollectionUtils.isNotEmpty(settingPriceGradientDTOS)) {
            settingPriceGradientDTOS.forEach(settingPriceGradientDTO -> {
                settingPriceGradientDTO.setCardId(cardId);
                settingPriceGradientDTO.setId(UUID.randomUUID().toString());
            });
        }

        memberCardService.save(dto);
        return ResultInfo.success("保存成功");
    }

    @ApiOperation(value = "修改会员卡信息", notes = "修改会员卡信息")
    @PostMapping("/update")
    public ResultInfo updateMemberCardInfo(@RequestBody MemberCardInfoBO cardInfoBO) {
        String cardId = cardInfoBO.getCardId();
        if (StringUtils.isEmpty(cardId)) {
            return ResultInfo.failed("会员卡不存在，可能登录已失效");
        }
        String cardName = cardInfoBO.getCardName();
        if (StringUtils.isEmpty(cardName)) {
            return ResultInfo.failed("会员卡名称不能为空");
        }
        List<String> cardSupportVenuesDTOS = cardInfoBO.getCardSupportVenuesDTOS();
        if (CollectionUtils.isEmpty(cardSupportVenuesDTOS)) {
            return ResultInfo.failed("会员卡支持场馆不能为空");
        }
        MemberCardBasicInfoVO memberCardBasicInfoVO = memberCardService.queryMemberCardBaseInfoByCardId(cardId);
        if (memberCardBasicInfoVO == null) {
            return ResultInfo.failed("会员卡不存在，可能登录已失效");
        }
        if (!StringUtils.equals(memberCardBasicInfoVO.getCardType(), cardInfoBO.getCardType())) {
            return ResultInfo.failed("会员卡类型不可修改");
        }
        MemberCardBasicInfoDTO dto = new MemberCardBasicInfoDTO();
        setMemberCardInfo(cardInfoBO, dto, cardId);
        memberCardService.update(dto);
        return ResultInfo.success("修改成功");
    }

    private void setMemberCardInfo(@RequestBody MemberCardInfoBO cardInfoBO, MemberCardBasicInfoDTO dto, String cardId) {
        dto.setCardId(cardId);
        dto.setCardName(cardInfoBO.getCardName());
        dto.setStatus("1");
        dto.setCardType(cardInfoBO.getCardType());
        dto.setCreateUser(getUsername());
        dto.setCreateTime(TimeUtils.getCurrentTime());
        dto.setLastModifyUser(getUsername());
        dto.setLastModifyTime(TimeUtils.getCurrentTime());

        CardSuperSettingsDTO cardSuperSettingsDTO = cardInfoBO.getCardSuperSettingsDTO();
        if (cardSuperSettingsDTO != null && StringUtils.isEmpty(cardSuperSettingsDTO.getId())) {
            cardSuperSettingsDTO.setId(StringUtils.getUUID());
            cardSuperSettingsDTO.setCardId(cardId);
        }
        dto.setCardSuperSettingsDTO(cardSuperSettingsDTO);

        CardTransferSettingsDTO cardTransferSettingsDTO = cardInfoBO.getCardTransferSettingsDTO();
        if (cardTransferSettingsDTO != null && StringUtils.isEmpty(cardTransferSettingsDTO.getId())) {
            cardTransferSettingsDTO.setId(StringUtils.getUUID());
            cardTransferSettingsDTO.setCardId(cardId);
        }
        dto.setCardTransferSettingsDTO(cardTransferSettingsDTO);

        dto.setCoursesSupportedCardDTOS(cardInfoBO.getCoursesSupportedCardDTOS());

        List<SettingPriceGradientDTO> settingPriceGradientDTOS = cardInfoBO.getSettingPriceGradientDTOS();
        if (CollectionUtils.isNotEmpty(settingPriceGradientDTOS)) {
            settingPriceGradientDTOS.forEach(spg -> {
                spg.setId(StringUtils.getUUID());
                spg.setCardId(cardId);
            });
        }

        dto.setSettingPriceGradientDTOS(settingPriceGradientDTOS);
        List<String> cardSupportVenuesList = cardInfoBO.getCardSupportVenuesDTOS();
        List<CardSupportVenuesDTO> cardSupportVenuesDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cardSupportVenuesList)) {
            cardSupportVenuesList.forEach(venuesId -> {
                CardSupportVenuesDTO csv = new CardSupportVenuesDTO();
                csv.setCardId(cardId);
                csv.setId(StringUtils.getUUID());
                csv.setVenuesId(venuesId);
                cardSupportVenuesDTOS.add(csv);
            });
        }
        dto.setCardSupportVenuesDTOS(cardSupportVenuesDTOS);
    }

    @ApiOperation(value = "删除会员卡信息", notes = "删除会员卡信息")
    @GetMapping("/delete")
    public ResultInfo deleteMemberCardInfoByCardId(@RequestParam("id") String id) {
        List<MemberCardBindingInfoDTO> memberCardBindingInfoDTOS
                = memberCardBindingInfoService.selectMemberCardBindingListByCardId(id);
        if (CollectionUtils.isNotEmpty(memberCardBindingInfoDTOS)) {
            return ResultInfo.failed("该会员卡已出售，不可删除！");
        }
        memberCardService.deleteMemberCardInfoByCardId(id);
        return ResultInfo.success("删除成功");
    }

    @ApiOperation(value = "查询会员卡信息详情", notes = "课程信息中已关联的课程有关系信息，未关联的则只有课程id名称类型,ManyClassCourses:大班SmallClassCourses:小班;PrivateClassCourses:私教")
    @PostMapping("/queryMemberCardInfoByCardId")
    public ResultInfo queryMemberCardInfoByCardId(String cardId) {
        try {
            MemberCardInfoVO vo = memberCardService.queryMemberCardInfoByCardId(cardId);
            // TODO  需要判断是否可以删除
            vo.setCanModified(true);
            return ResultInfo.success(vo);
        } catch (Exception e) {
            logger.error("cardId: " + cardId, e);
            return ResultInfo.failed("服务器异常，请联系运营商！");
        }
    }

    @ApiOperation(value = "查询会员卡详情列表", notes = "查询会员卡详情列表")
    @PostMapping("/list")
    public ResultInfo queryMemberCardList(@RequestBody MemberCardBasicInfoBo dto) {
        List<MemberCardBasicInfoVO> list = memberCardService.selectMemberCardInfoList(dto);
        PageInfo<MemberCardBasicInfoVO> pageInfo = new PageInfo<>(list);
        return ResultInfo.success(pageInfo);
    }

    @ApiOperation(value = "绑卡-查询所有会员卡", notes = "绑卡-查询所有会员卡,续卡传cardId 查询该会员卡信息")
    @PostMapping("/queryAllMemberCard")
    public ResultInfo queryAllMemberCard(@RequestParam(value = "cardId", required = false) String cardId) {
        List<MemberCardVo> list = memberCardService.queryAllMemberCard(cardId);
        return ResultInfo.success(list);
    }

    @ApiOperation(value = "会员绑卡-查询所有会员卡", notes = "绑卡-查询所有会员卡,续卡传cardId 查询该会员卡信息")
    @PostMapping("/queryBindCardList")
    public ResultInfo queryBindCardList(@RequestBody BindCardBo bo) {
        List<BindCardVo> list = memberCardService.queryBindCardList(bo);
        PageInfo<BindCardVo> pageInfo = new PageInfo<>(list);
        return ResultInfo.success(pageInfo);
    }


    @ApiOperation(value = "绑卡保存", notes = "绑卡保存")
    @PostMapping("/memberBindCard")
    public ResultInfo memberBindCard(@RequestBody MemberConsumeRecordDTO dto) {
        // 查询是否已绑定该卡
        MemberCardBindingInfoDTO bindingInfo =  memberCardBindingInfoMapper.selectByCardIdAndMemberId(dto.getCardId(),dto.getMemberId());
        if(bindingInfo != null){
            return ResultInfo.failed("该卡已绑定，请勿重复绑卡");
        }else{
            memberCardService.memberBindCard(dto);
        }
        return ResultInfo.success("保存成功");
    }

    @ApiOperation(value = "续卡-会员卡充值保存", notes = "续卡-会员卡充值保存")
    @PostMapping("/memberRenewCard")
    public ResultInfo memberRenewCard(@RequestBody MemberConsumeRecordDTO dto) {
        MemberCardBindingInfoDTO bindingInfo =  memberCardBindingInfoMapper.selectByCardIdAndMemberId(dto.getCardId(),dto.getMemberId());
        dto.setBindingCardId(bindingInfo.getId());
        memberCardService.memberRenewCard(dto);
        return ResultInfo.success("续卡成功");
    }

    @ApiOperation(value = "扣费", notes = "扣费")
    @PostMapping("/memberCardDeductMoney")
    public ResultInfo memberCardDeductMoney(@RequestBody MemberCardDeductMoneyPo po) {
        MemberCardBindingInfoDTO bindingInfo =  memberCardBindingInfoMapper.selectByCardIdAndMemberId(po.getCardId(),po.getMemberId());
        po.setBindingCardId(bindingInfo.getId());
        memberCardService.memberCardDeductMoney(po);
        return ResultInfo.success("扣费成功");
    }

    @ApiOperation(value = "停卡", notes = "停卡")
    @PostMapping("/memberCardStop")
    public ResultInfo memberCardStop(@RequestBody MemberCardStopPo po) {
        MemberCardBindingInfoDTO bindingInfo =  memberCardBindingInfoMapper.selectByCardIdAndMemberId(po.getCardId(),po.getMemberId());
        po.setBindingCardId(bindingInfo.getId());
        memberCardService.memberCardStop(po);
        return ResultInfo.success("扣费成功");
    }
    @ApiOperation(value = "激活会员卡", notes = "激活会员卡")
    @PostMapping("/memberCardActivate")
    public ResultInfo memberCardActivate(@RequestBody MemberCardStopPo po) {
        MemberCardBindingInfoDTO bindingInfo =  memberCardBindingInfoMapper.selectByCardIdAndMemberId(po.getCardId(),po.getMemberId());
        po.setBindingCardId(bindingInfo.getId());
        memberCardService.memberCardActivate(po);
        return ResultInfo.success("激活成功");
    }
    @ApiOperation(value = "根据课程id查询会员卡信息详情列表", notes = "根据课程id查询会员卡信息详情列表")
    @PostMapping("/queryMemberCardInfoByCourseId")
    public ResultInfo queryMemberCardInfoByCourseId (@RequestParam("courseId") String courseId) {
        try {
            List<MemberCardInfoVO> vos = memberCardService.queryMemberCardInfoByCourseId(courseId);
            // TODO  需要判断是否可以删除
            //vos.setCanModified(true);
            return ResultInfo.success(vos);
        } catch (Exception e) {
            logger.error("根据课程id查询会员卡信息详情列表 courseId: " + courseId, e);
            return ResultInfo.failed("服务器异常，请联系运营商！");
        }
    }

    /**
     * 查询会员消费记录
     * @param
     * @return
     */
    @ApiOperation(value = "查询会员的会员卡详情", notes = "查询会员的会员卡详情,memberId cardId")
    @PostMapping("/getMemberCardInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "cardId", value = "会员卡id", dataType = "string", paramType = "query")}
    )
    public ResultInfo getMemberCardInfo(@RequestBody Map<String,String> map) {
        String memberId = map.get("memberId");
        String cardId = map.get("cardId");
        if(StringUtils.isBlank(memberId)){
            return ResultInfo.failed("会员id不能都为空");
        }
        if(StringUtils.isBlank(memberId)){
            return ResultInfo.failed("会员卡id不能都为空");
        }
        MemberCardInfoDTO dto = memberCardService.getMemberCardInfo(memberId,cardId);
        return ResultInfo.success(dto);
    }
}
